(function ($) {
  "use strict";
  $.fn.gCalendar = function (option) {
    var defaults = {
      bg: 'https://10068482.s21i.faiusr.com/2/ABUIABACGAAg7L_XvAUozID0iwcwgA846gU.jpg',
      bgs: '',
      num: 1, // 日历个数 Number
      date: {
        '2018-10-10': {
          title: "test"
        }
      },
      clickFn: function (res, self) {
        // console.log(res)
      }
    };
    var params = $.extend(defaults, option);
    var self = $(this);
    var today = new Date();
    var calendar = {
      init: function () {
        var next_month, month_list, tpl;
        if (self.find(".ecgo-calendar").length === 0){
          var monthArr = [];
          var firstMonth;
          if (self.data("date")) {
            firstMonth = new Date(self.data("date"));
          }else{
            firstMonth = today
          }
          monthArr.push(firstMonth);
          if(params.num>1){
            for(var i=1;i<params.num;i++){
              next_month = new Date(firstMonth.getFullYear(), firstMonth.getMonth() + i, 1);
              monthArr.push(next_month)
            }
          }
          month_list = calendar.getMonthDay(monthArr);
          tpl = '<div class="ecgo-calendar"><span class="prev-btn"></span><span class="next-btn"></span><div class="calendar-group"></div></div></div>';
          self.append(tpl);
          if ($(window).width() > 425) {
            self.find(".ecgo-calendar").css('background-image', 'url('+params.bg+')');
          }else{
            self.find(".ecgo-calendar").css('background-image', 'url('+params.bgs+')');
          }
          calendar.initEvent(month_list);
        }
      },
      initEvent: function (list) {
        calendar.baseCalendar(list);
        calendar.prevClick();
        calendar.nextClick();
        calendar.groupEvent();
        $('[data-toggle="tooltip"]').tooltip()
      },
      getMonthDay: function (months) {
        var all_months = [];
        for (var i = 0; i < months.length; i++) {// 遍历月
          var month_days = [];
          var date_num = getMonthDateNumber(months[i]);// 获取一个月的天数
          var firstDay = new Date(months[i].getFullYear(), months[i].getMonth(), 1);
          for (var j=0;j<date_num+firstDay.getDay();j++){// 遍历天
            var tem_date;
            var curMonth = true;
            if (j < firstDay.getDay()) { // 小于今日
              tem_date = new Date(firstDay.getTime() - (firstDay.getDay() - j) * 24 * 60 * 60 * 1000);
              curMonth = false;
            } else if (j >= firstDay.getDay() && j < firstDay.getDay() + date_num) { // 当月
              tem_date = new Date(months[i].getFullYear(), months[i].getMonth(), (j-firstDay.getDay()) + 1);
              curMonth = true;
            } else { // 下个月
              tem_date = new Date(firstDay.getTime() + (j-firstDay.getDay()) * 24 * 60 * 60 * 1000);
              curMonth = false;
            }
            var todayDate = today.getFullYear() + "-" + dbDate(today.getMonth() + 1)  + "-" + dbDate(today.getDate());
            var fullyear = tem_date.getFullYear() + "-" + dbDate(tem_date.getMonth() + 1) + "-" + dbDate(tem_date.getDate());
            month_days.push({
              ymd: fullyear,
              year: tem_date.getFullYear(),
              month: tem_date.getMonth() + 1,
              date: tem_date.getDate(),
              week: tem_date.getDay(),
              disable: new Date(fullyear) < new Date(todayDate),
              curMonth: curMonth,
              title: (params.date[fullyear] && params.date[fullyear].title)?params.date[fullyear].title:null
            })
          }
          all_months.push(month_days);
        }
        // console.log(all_months);
        return all_months;
      },
      baseCalendar: function (monthList) {
        var date_tpl = '';
        var week_tpl = '';
        var week = ['日','一','二','三','四','五','六'];
        var calendarGroup = self.find(".calendar-group");
        calendarGroup.html('');
        for (var i=0;i<week.length;i++){
          week_tpl += '<span>'+ week[i] +'</span>';
        }
        for (var i=0;i<monthList.length;i++) {
          var year = monthList[i][6].year;
          var month = monthList[i][6].month;
          var ym = year + "年" + month + "月";
          var first_day = monthList[i][0].week;
          date_tpl += '<div class="calendar-item">'+
            '<div class="calendar-tit" data-year="'+year+'" data-month="'+month+'">'+ym+'</div>'+
            '<div class="calendar-box"><div class="calendar-week">'+week_tpl+'</div>'+
            '<div class="calendar-daylist">';
          for(var j=0;j<monthList[i].length+first_day;j++){
            var dateblank = '';
            if(monthList[i][j].curMonth){
              dateblank = '<div class="date-grid'+
                (monthList[i][j].disable?' disable':'')+ '"'+
                (monthList[i][j].title?' data-toggle="tooltip" title="'+monthList[i][j].title+'" data-placement="bottom"':'')+
                ' data-ymd="'+monthList[i][j].ymd+'">'+
                '<div class="day-item">'+monthList[i][j].date+'</div>'+
                '</div>';
            }
            date_tpl += '<span class="daylist-blank">'+dateblank+'</span>';
          }
          date_tpl += '</div></div></div>';
        }
        calendarGroup.append(date_tpl);
      },
      prevClick: function () {// 左点击
        self.find(".prev-btn").on("click", function () {
          var month_list;
          var all_month = [];
          self.find(".calendar-item").each(function () {
            var prev_month = new Date(parseInt($(this).find(".calendar-tit").data("year")), parseInt($(this).find(".calendar-tit").data("month")) - 2, 1);
            month_list = calendar.getMonthDay([prev_month]);
            all_month.push(month_list[0]);
          });
          calendar.baseCalendar(all_month);
          calendar.groupEvent();
        })
      },
      nextClick: function () {// 右点击
        self.find(".next-btn").on("click", function () {
          var month_list;
          var all_month = [];
          self.find(".calendar-item").each(function () {
            var next_month = new Date(parseInt($(this).find(".calendar-tit").data("year")), parseInt($(this).find(".calendar-tit").data("month")), 1);
            month_list = calendar.getMonthDay([next_month]);
            all_month.push(month_list[0]);
          });
          calendar.baseCalendar(all_month);
          calendar.groupEvent();
        })
      },
      groupEvent: function () {// 日历事件
        self.find(".date-grid").on("click",function () {
          if (!$(this).hasClass("disable")) {
            var obj = {
              date: $(this).data("ymd"),
              title: $(this).data("original-title")
            }
            params.clickFn(obj);
          }
        })
      }
    };
    // 获取一个月的天数
    function getMonthDateNumber(date) {
      var tem_date = new Date(date.getFullYear(), date.getMonth() + 1, 0);
      return tem_date.getDate();
    }
    // 格式化日期
    function dbDate(date) {
      date = date.toString();
      date = date.length === 1 ? "0" + date : date;
      return date;
    }
    calendar.init()
  };
})(jQuery);
